<template>
  <el-form size="large" ref="loginFormRef" class="login-form" :rules="loginRules" :model="loginForm" label-width="0">
    <el-form-item prop="username">
      <el-input
        :prefix-icon="User"
        v-model="loginForm.username"
        @keyup.enter="handleLogin"
        clearable
        placeholder="请输入账号"></el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        @keyup.enter="handleLogin(loginFormRef)"
        :prefix-icon="Lock"
        show-password
        clearable
        placeholder="请输入密码"></el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-input
        :prefix-icon="Key"
        v-model="loginForm.code"
        @keyup.enter="handleLogin(loginFormRef)"
        clearable
        placeholder="请输入验证码">
        <template v-slot:append>
          <verifyication-code v-model:code="imgCode"></verifyication-code>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button :loading="loading" @click="handleLogin(loginFormRef)" type="primary" size="small" class="login-submit">
        登录
      </el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { VALIDATE_PASSWORD } from "@/utils/validate";
import { clearStore } from "@/utils/localStorage";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { User, Lock, Key } from "@element-plus/icons-vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import VerifyicationCode from "@/components/VerifyicationCode/index.vue";
import { useRouter } from "vue-router";

const router = useRouter();
defineOptions({
  name: "UserLogin"
});
/** 验证码组件 */
const imgCode = ref("");
/** 监听验证码并赋值 */
watch(imgCode, (newVal) => {
  useUserStoreHook().setVerifyCode(newVal);
});
/** 登录表单元素的引用 */
const loginFormRef = ref<FormInstance>();
/** 登录按钮 Loading */
const loading = ref(false);
/** 登录表单数据 */
const loginForm = reactive({
  username: "",
  password: "",
  code: ""
});
/** 登录表单校验规则 */
const loginRules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [
    {
      validator: (_rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入密码"));
        } else if (!VALIDATE_PASSWORD.test(value)) {
          callback(new Error("密码格式应为8-18位数字、字母、符号的任意两种组合"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  code: [
    {
      validator: (_rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入验证码"));
        } else if (useUserStoreHook().verifyCode !== value) {
          callback(new Error("请输入正确的验证码"));
        }
        {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
});
/** 登录按钮点击事件 */
const handleLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername(loginForm)
        .then((res: any) => {
          if (res.code === 200) {
            // 获取后端路由
            usePermissionStoreHook()
              .getMenuRouter()
              .then(() => {
                if (!usePermissionStoreHook().asyncMenus.length) {
                  clearStore({});
                  return ElMessage({
                    message: "暂无菜单",
                    type: "warning"
                  });
                }
                ElMessage({
                  message: res.msg,
                  type: "success"
                });
                router.push(usePermissionStoreHook().asyncMenus[0].path);
              });
          }
        })
        .catch(() => {
          imgCode.value = "";
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      console.error("表单校验不通过", fields);
    }
  });
};
</script>
<style scoped lang="scss"></style>
